package com.javabank.ws.dao.impl;

import java.util.Date;
import java.util.List;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import com.javabank.ws.dao.TransactionDAO;
import com.javabank.ws.domain.Account;
import com.javabank.ws.domain.Account_;
import com.javabank.ws.domain.Transaction;
import com.javabank.ws.domain.Transaction_;

public class TransactionDAOImpl extends BaseDAOImpl<Transaction> implements TransactionDAO {
	public TransactionDAOImpl() {
		
	}
	
	public Transaction[] getTransactionsByReknr(int reknr, Date date) {
		open();
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Transaction> query = cb.createQuery(Transaction.class);
        Root<Transaction> t = query.from(Transaction.class);
        
        // Joins met verzender ontvanger opzetten
        Join<Transaction, Account> a1 = t.join(Transaction_.from);
        Join<Transaction, Account> a2 = t.join(Transaction_.to);
        
        // Where maken
        Predicate condition =
        	// Eerst een and
        	cb.and(
	        	cb.or(
	        		// Of rekeningnummer is gelijk aan ontvanger, of verzender
	        		cb.equal(a1.get(Account_.rekeningnummer), reknr),
	        		cb.equal(a2.get(Account_.rekeningnummer), reknr)
	        	),
	        	// Datum is groter of gelijk
	        	cb.greaterThanOrEqualTo(t.<Date>get("datum"), date)
	        );
        
        query.where(condition);
        
        TypedQuery<Transaction> typedQuery = em.createQuery(query);
        List<Transaction> result = typedQuery.getResultList();
        
        if(result.size() > 0){
        	return result.toArray(new Transaction[result.size()]);
        }else{
        	return null;
        }
	}
}
